package com.zhanghs.contentcenter.filter;

import com.zhanghs.contentcenter.util.TraceIdContext;
import com.zhanghs.contentcenter.util.TraceIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhanghongshan
 * @date 2021/10/2 6:52 下午
 */
@Slf4j
public class RequestUrlFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取http信息
        long start = System.currentTimeMillis();
        HttpServletRequest request= (HttpServletRequest) servletRequest;

        request.setCharacterEncoding("UTF-8");
        // 设置 请求链路 traceid
        String requestId = request.getHeader(TraceIdContext.TRACE_ID_KEY);
        if (StringUtils.isNotEmpty(requestId)) {
            TraceIdContext.setTraceId(requestId);
        } else {
            TraceIdContext.setTraceId(TraceIdUtils.getTraceId());
        }
        //请求包装类
        RequestWrapper requestWrapper = new RequestWrapper(request);
        //请求参数
        String params = StringUtils.isNotBlank(requestWrapper.getBody())?requestWrapper.getBody():requestWrapper.getQueryString();
        Map<String,String> requestMap = new HashMap<>();
        requestMap.put("host",request.getRemoteHost());
        requestMap.put("uri",request.getRequestURI());
        requestMap.put("method",request.getMethod());
        requestMap.put("params",params);
        log.info("request:{}",requestMap);

        servletResponse.setContentType("application/json");
        servletResponse.setCharacterEncoding("UTF-8");
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) servletResponse);
        filterChain.doFilter(requestWrapper,responseWrapper);
        //响应参数
        String responseStr = new String(responseWrapper.getResponseData());
        servletResponse.setContentLength(responseStr.getBytes().length);
        OutputStream outputStream = servletResponse.getOutputStream();
        outputStream.write(responseStr.getBytes(),0,responseStr.getBytes().length);
        outputStream.flush();
        outputStream.close();
        long end = System.currentTimeMillis();
        log.info("resonse:timed:{} ms,body:{}",end-start,responseStr);

    }

    @Override
    public void destroy() {
        // 销毁 请求链路 traceid
        TraceIdContext.removeTraceId();
    }
}
